using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Diagnostics;

namespace StarTrek
{
    /// <summary>
    /// This class is responsible for communicating with the server app and for starting
    /// up VLC (Video Lan Client.)
    /// </summary>
    class TVClient
    {
        private Socket server;
        private Process p;
        private string serverIP = Properties.Settings.Default.TVServerIP;
        private int serverPort = Properties.Settings.Default.TVServerPort;
        private int streamPort = Properties.Settings.Default.TVStreamPort;

        /// <summary>
        /// Connect to the server and await further commands.
        /// </summary>
        public TVClient()
        {
            byte[] data = new byte[1024];
            string stringData;
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(serverIP), serverPort);
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            server.Connect(ipep);

            int recv = server.Receive(data);
            stringData = Encoding.ASCII.GetString(data, 0, recv);
        }

        /// <summary>
        /// Make a request to the server to start a specific stream. Wait a few seconds
        /// for the server to begin and then execute VLC in full screen mode
        /// </summary>
        /// <param name="channel"></param>
        public void StartChannel(int channel)
        {
            byte[] data = new byte[1024];
            int recv;
            string stringData;
            string input = "start " + channel.ToString();

            server.Send(Encoding.ASCII.GetBytes(input));
            data = new byte[1024];
            recv = server.Receive(data);
            stringData = Encoding.ASCII.GetString(data, 0, recv);

            // wait for the server to start the server
            System.Threading.Thread.Sleep(5000);

            // Fire up VLC to receive the stream.
            p = new Process();
            p.StartInfo.WorkingDirectory = @"c:\program files\videolan\vlc";
            p.StartInfo.FileName = @"vlc.exe";
            p.StartInfo.Arguments = String.Format("--fullscreen http://{0}:{1}", serverIP, streamPort.ToString());
            p.Start();
        }

        /// <summary>
        /// Tell the server to stop streaming and then end VLC.
        /// </summary>
        public void StopClient()
        {
            // Console.WriteLine("Disconnecting from server...");
            server.Send(Encoding.ASCII.GetBytes("stop"));
            System.Threading.Thread.Sleep(1000);
            server.Shutdown(SocketShutdown.Both);
            server.Close();
            p.Kill();
        }
    }
}
